include('shared.lua')

// Materials

local Materials = {}

// Set material

function ENT:Material(Texture)
	if (Materials[Texture]) then
		return Materials[Texture]
	else
		Materials[Texture] = Material(Texture)
		
		return Materials[Texture]
	end
end

// Draw

function ENT:Draw()
	if (LocalPlayer():GetEyeTrace().Entity == self.Entity && EyePos():Distance(self.Entity:GetPos()) < 512) then
		self:DrawEntityOutline(1.0)
		
		if (self:GetOverlayText() != "") then
			AddWorldTip(self.Entity:EntIndex(), self:GetOverlayText(), 0.5, self.Entity:GetPos(), self.Entity)
		end
	end
	
	// Position
	
	local Position = self.Entity:GetPos()
	
	// X, Y and Z
	
	local X = self.Entity:GetNetworkedInt("X")
	local Y = self.Entity:GetNetworkedInt("Y")
	local Z = self.Entity:GetNetworkedInt("Z")
	
	// Active
	
	if not (self.Entity.Active) then
		if (X != 0 and Y != 0 and Z != 0) then
			// Render bounds
			
			local Minimum = Vector(-X, -Y, -Z)
			local Maximum = Vector(X, Y, Z)
			
			self.Entity:SetRenderBounds(Minimum, Maximum)
			
			// Active
			
			self.Entity.Active = true
		end
	else
		local Texture = self.Entity:GetMaterial()
		
		// Check
		
		if (Texture == "") then Texture = "models/wireframe" end
		
		// Material
		
		local Material = self:Material(Texture)
		
		// Material
		
		render.SetMaterial(Material)
		
		// Colour
		
		local Colour = Color(255, 255, 255, 255)

		// Quad
		
		self:DrawAxisPlaneX(Position, X, Y, Z, Colour)
		self:DrawAxisPlaneY(Position, X, Y, Z, Colour)
		self:DrawAxisPlaneZ(Position, X, Y, Z, Colour)
		self:DrawAxisPlaneX(Position + Vector(X, Y, 0), -X, -Y, Z, Colour)
		self:DrawAxisPlaneY(Position + Vector(X, Y, 0), -X, -Y, Z, Colour)
		self:DrawAxisPlaneZ(Position + Vector(X, Y, Z), -X, -Y, Z, Colour)
		
		// Draw model
		
		self.Entity:DrawModel()
	end
end 

// Draw axis plane X

function ENT:DrawAxisPlaneX(Position, X, Y, Z, Colour)
	render.DrawQuadEasy(Position + Vector(0, Y / 2, Z / 2), Vector(-1, 0, 0), X, Z, Colour)
	render.DrawQuadEasy(Position + Vector(0, Y / 2, Z / 2), Vector(1, 0, 0), X, Z, Colour)
end

// Draw axis plane Y

function ENT:DrawAxisPlaneY(Position, X, Y, Z, Colour)
	render.DrawQuadEasy(Position + Vector(X / 2, 0, Z / 2), Vector(0, -1, 0), Y, Z, Colour)
	render.DrawQuadEasy(Position + Vector(X / 2, 0, Z / 2), Vector(0, 1, 0), Y, Z, Colour)
end

// Draw axis plane Z

function ENT:DrawAxisPlaneZ(Position, X, Y, Z, Colour)
	render.DrawQuadEasy(Position + Vector(X / 2, Y / 2, 0), Vector(0, 0, -1), X, Y, Colour)
	render.DrawQuadEasy(Position + Vector(X / 2, Y / 2, 0), Vector(0, 0, 1), X, Y, Colour)
end

// Initialize

function ENT:Initialize()
	self.Entity.Active = false
end